'''
This module manage the collection for each column in byhh.
'''
from pymongo import Connection

from infobyhh.settings import DB_LOCATION, DB_PORT, DB_NAME

DETAIL_SUFFIX = "_detail"


def make_detail_collection_name(boardname):
    return "%s%s" % (boardname, DETAIL_SUFFIX)

class ColumnCollection(object):
    '''
    The data structure in the column collection:
        [
            {
                "num": "12",
                "user_name": "shifan",
                "datetime": "11th Nov",
                "title": "hey, body.",
                "click": "5",
                "file": "M.1231244.A",
            },
            {
                "num": "12",
                "user_name": "shifan",
                "datetime": "11th Nov",
                "title": "hey, body.",
                "click": "5",
                "file": "M.1231244.A",
            },
            {
                "num": "12",
                "user_name": "shifan",
                "datetime": "11th Nov",
                "title": "hey, body.",
                "click": "5",
                "file": "M.1231244.A",
            },
        ]

    The data structure in the column detail collection:

    '''

    def __init__(self, board_name, location=DB_LOCATION, port=DB_PORT, db=DB_NAME):
        '''
        Init the database connection. Hold the connection to collection "board" and "board_detail".
        '''
        board_detail_name = make_detail_collection_name(self.board)

        self.conn = Connection(location, port)
        self.db = self.conn[DB_NAME]
        self.board = self.db[board_name]
        self.board_detail = self.db[board_detail_name]

    def insert_list(self, docs):
        '''
        Insert documents to collection "board".
        '''
        self.board.insert(docs)

    def get_last_num(self):
        '''
        '''
        last_doc = self.board.find().sort({"num": -1}).limit(1)
        if last_doc:
            last_num = int(last_doc["num"])
            return last_num
        return None

    def insert_details(self, details):
        '''
        Insert documents to collection "board_detail".
        '''
        self.board_detail.insert(details)

    
